package com.dicsystems.myrec;

import java.util.ArrayList;
import java.util.List;

import com.dicsystems.myrec.dto.Image;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;

public class ImageAdapter extends ArrayAdapter<Image> {

	private Context me;
	private int resource;
	private LayoutInflater inflater;
	protected List<Image> images = new ArrayList<Image>();

	protected ImageAdapter(Context context, int resource, List<Image> images) {
		super(context, resource, images);
		this.me = context;
		this.resource = resource;
		this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.images = images;
	}

	private class ViewHolder {
		ImageButton image;
		CheckBox check;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if(convertView == null) {
			convertView = inflater.inflate(resource, null);
			holder = new ViewHolder();
			holder.image = (ImageButton)convertView.findViewById(R.id.image);
			holder.check = (CheckBox)convertView.findViewById(R.id.check);
			convertView.setTag(holder);
		}
		else {
			holder = (ViewHolder)convertView.getTag();
		}
		final Image image = getItem(position);
		holder.image.setImageBitmap(getImage(image.path));
		holder.image.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				showImage(image.path);
			}
		});
		holder.check.setChecked(image.check);
		holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) {
					//list.add(image.path);
				}
				else {
					images.remove(images.indexOf(image.path));
				}
			}
		});
		return convertView;
	}

	private Bitmap getImage(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		options.inSampleSize = Math.max(options.outWidth / 480 + 1, options.outHeight / 800 + 1);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(path, options);
	}

	private void showImage(String path) {
		ImageView image = new ImageView(me);
		image.setImageBitmap(getImage(path));
		AlertDialog.Builder builder = new AlertDialog.Builder(me);
		builder.setView(image);
		builder.setPositiveButton(R.string.close, null);
		builder.show();
	}
}
